﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.ComponentModel;
using System.Linq.Dynamic;

namespace Catalyst.Web.DynamicData
{
    /// <summary>
    /// A parameter responsible for creating a LambdaExpression that performs equality.
    /// </summary>
    public class EqualsExpressionParameter : DynamicExpressionParameterBase
    {
        public EqualsExpressionParameter() { }

        /// <summary>
        /// The type of the value to be comparred against
        /// </summary>
        public TypeCode ValueType
        {
            get
            {
                object obj2 = this.ViewState["ValueType"];
                if (obj2 == null)
                {
                    return TypeCode.Empty;
                }
                return (TypeCode)obj2;
            }
            set
            {
                if (this.Type != value)
                {
                    this.ViewState["ValueType"] = value;
                    this.OnParameterChanged();
                }
            }
        }

        /// <summary>
        /// The string representation of the value
        /// </summary>
        [DefaultValue("")]
        public string Value
        {
            get
            {
                object obj2 = this.ViewState["Value"];
                if (obj2 == null)
                {
                    return null;
                }
                return (string)obj2;
            }
            set
            {
                if (this.Value != value)
                {
                    this.ViewState["Value"] = value;
                    this.OnParameterChanged();
                }
            }
        }

        /// <summary>
        /// Dynamically creates a LambdaExpression that compares the Value to the Property defined by Name
        /// </summary>
        /// <param name="itType">The type of object the LambdaExpression is evaluated against.</param>
        /// <returns>A LambdaExpression that creates an Equals Expression</returns>
        public override LambdaExpression GetLambdaExpression(Type itType)
        {
            if (string.IsNullOrEmpty(Value))
                return null;

            object typedValue = GetValue(Value, "", ValueType, true, false);
            return DynamicExpression.ParseLambda(itType, typeof(bool), string.Format("{0} == @0", this.Name), typedValue);
        }
    }
}
